package cn.mrcode.fd.blog.controller;

import cn.mrcode.fd.blog.buutil.ResultJsonUtil;
import cn.mrcode.fd.blog.buutil.restfull.RestFulResultUtil;
import cn.mrcode.fd.blog.cache.service.IArticleCache;
import cn.mrcode.fd.blog.common.BaseController;
import cn.mrcode.fd.blog.common.BusConstant;
import cn.mrcode.fd.blog.dto.article.NewResData;
import cn.mrcode.fd.blog.entity.Article;
import cn.mrcode.fd.blog.entity.Category;
import cn.mrcode.fd.blog.entity.LoginInfo;
import cn.mrcode.fd.blog.entity.User;
import cn.mrcode.fd.blog.entityCu.ArticleCu;
import cn.mrcode.fd.blog.exception.BlogException;
import cn.mrcode.fd.blog.services.IAccountService;
import cn.mrcode.fd.blog.services.IArticleService;
import cn.mrcode.fd.blog.services.ICategoryService;
import cn.mrcode.fd.blog.services.IUserService;
import cn.mrcode.fd.utils.mybatis.page.Page;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

/**
 * @author zhuqiang
 * @version V1.0
 * @date 2015/12/3 22:14
 */
@Controller
public class ArticleController extends BaseController{
    @Autowired
    private IArticleService iArticleService;
    @Autowired
    private IAccountService iAccountService;
    @Autowired
    private IUserService iUserService;
    @Autowired
    private ICategoryService iCategoryService;
    @Autowired
    private IArticleCache iArticleCache;
    
    /**
     * 账户主页
     * @param model
     * @return
     */
    @RequestMapping("/{account}")
    public String index(Model model,@PathVariable String account){
        LoginInfo loginInfo = iAccountService.findByAccount(account);
        if(loginInfo == null){
            response.setStatus(404);
            return "/404";
        }
        model.addAttribute("account",account);
        return "redirect:/"+account+"/article/list";
    }

    /**
     * 加载文章列表,正常发布的文章列表
     * @param pageNo
     * @param account
     * @return
     */
    @RequestMapping(value = "/{account}/article/list" /*, produces = "application/json;charset=utf-8"*/)
    public String queryAll(Model model,@PathVariable String account ,Integer pageNo) throws Exception {
        pageNo = pageNo == null? 1:pageNo;
        Page<ArticleCu> page = new Page<ArticleCu>();
        page.setPageNo(pageNo);
        page.setPageSize(10);
        Page<ArticleCu> articlePage = iArticleService.queryAll(page,account, BusConstant.ArticleStatus.NORMAL);

        model.addAttribute("articlePage",articlePage);
        model.addAttribute("account",account);
        model.addAttribute("user",iUserService.findUserConfig(account));
        return "/article/article_all";
    }

    @RequestMapping(value = "/article/allstation" /*, produces = "application/json;charset=utf-8"*/)
    public String queryAll(Model model,Integer pageNo) throws Exception {
        pageNo = pageNo == null? 1:pageNo;
        Page<ArticleCu> page = new Page<ArticleCu>();
        page.setPageNo(pageNo);
        page.setPageSize(5);
        Page<ArticleCu> articlePage = iArticleService.queryAllOrderBy(page,"READ_NUM","DESC");

        model.addAttribute("articlePage",articlePage);
        return "/article/article_allstation";
    }

    /**
     * 从缓存获取全站热门文章
     * @param model
     * @param pageNo
     * @return
     */
    @RequestMapping("/article/topmore")
    public String moreAllTop(Model model,Integer pageNo){
        pageNo = pageNo == null? 1:pageNo;
        int pageSize = 10;
        Page<Article> result =  iArticleCache.getMoreAllTop(pageNo,pageSize);
        model.addAttribute("articlePage",result);
        return "/article/article_moretop";
    }

    @RequestMapping(value = "/{account}/article/category/{categoryId}")
    public String queryAllByCategory(Model model,Integer pageNo,@PathVariable String account,@PathVariable String categoryId) throws Exception {
        pageNo = pageNo == null? 1:pageNo;
        Page<ArticleCu> page = new Page<ArticleCu>();
        page.setPageNo(pageNo);
        page.setPageSize(10);
        Page<ArticleCu> articlePage = null;
        if("all".equals(categoryId)){
            articlePage = iArticleService.queryAll(page,account, BusConstant.ArticleStatus.NORMAL);
        }else{
            articlePage = iArticleService.queryAllByCategory(page,categoryId);
        }

        List<Category> categorys = iCategoryService.findAllByAccount(account);
        model.addAttribute("categorys",categorys);

        model.addAttribute("articlePage",articlePage);
        model.addAttribute("account",account);
        model.addAttribute("user",iUserService.findUserConfig(account));
        model.addAttribute("catId",categoryId);
        return "/article/article_list_by_category";
    }


    @RequestMapping(value = "/auth/article/create_pre",produces = "application/json;charset=utf-8")
    public String createPre(Model resultModel){
        String userAccount = getUser().getAccount();
        ArticleCu articleVo = iArticleService.createPre(userAccount);
        resultModel.addAttribute("articleVo",articleVo);
        return "/article/article_add";
    }

    @RequestMapping(value = "/auth/article/new",produces = "application/json;charset=utf-8")
    public String newArticle(Model model){
        try {
            String userAccount = getUser().getAccount();
            NewResData newResData = iArticleService.newData(userAccount);
            if(!newResData.isSuccess()){
                return "error";
            }
            model.addAttribute("newResData",newResData);
            return "/article/article_add";
        }catch (BlogException e){
            return "error";
        }
    }

    /**
     * 新建文章，获取初始化文本
     * @return
     */
    @RequestMapping(value = "/auth/article/newbody",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String newbody(){
        return "[TOCM]\n" +
                "\n" +
                "hello,mrcode blog! 本博客使用MarkDown语法编辑器，如有不会的请点击工具栏中的使用帮助(问号图标)";
    }



    @RequestMapping(value = "/auth/article/create_submit",produces = CHARSET_UTF8_JSON)
    @ResponseBody
    public String createSubmit(ArticleCu articleCu) throws Exception {
        User user = getUser();
        if(user == null){
            return  RestFulResultUtil.fail("登录已超时，请另开一个页面登录之后，再提交本次操作").serializeJson();
        }
        String articleId = iArticleService.insert(articleCu, user);
        JSONObject result = new JSONObject();
        result.put("result","success");
        result.put("redirectUrl", String.format("%s%s/article/details/%s.html",getDomain(),user.getAccount(),articleId));
        return RestFulResultUtil.success(result).serializeJson();
    }

    /**
     * 加载文章详情：正常发布的文章详情
     * @param id
     * @param model
     * @return
     */
    @RequestMapping(value = "/{account}/article/details/{id}.html")
    public String details(@PathVariable String account,@PathVariable String id,Model model) throws Exception {
        ArticleCu articleVo = iArticleService.findById(id);
        if(articleVo == null){
            response.setStatus(404);
            return "/404";
        }

        if(articleVo.getStatus().intValue() == BusConstant.ArticleStatus.SHIELD){
            response.setStatus(404);
            return "/404";
        }

        if(articleVo.getStatus().intValue() != BusConstant.ArticleStatus.NORMAL){
            response.setStatus(404);
            return "/404";
        }

        model.addAttribute("articleVo",articleVo);
        model.addAttribute("account",account);
        model.addAttribute("user",iUserService.findUserConfig(account));

        return "/article/article_detail";
    }

    /**
     * 加载文章单独的字段
     * @param account
     * @param articleId
     * @return
     */
    @RequestMapping(value = "/{account}/article/details/body/{articleId}",produces = CHARSET_UTF8_JSON)
    @ResponseBody
    public String detailsBody(@PathVariable String account,@PathVariable String articleId){
        String body = iArticleService.loadDetailsBody(articleId);
        return body;
    }

    /**
     * 编辑文章前的查询
     * @param id
     * @param resultMap
     * @return
     */
    @RequestMapping(value = "/auth/article/edit_pre/{id}")
    public String edit_pre(@PathVariable String id, Map<String,Object> resultMap){
        User user = getUser();
        ArticleCu articleVo = iArticleService.find(user.getAccount(),id);
        resultMap.put("articleVo",articleVo);
        return "/article/article_edit";
    }

    /**
     * 编辑文章保存
     * @param articleCu
     * @param
     * @return
     */
    @RequestMapping(value = "/auth/article/edit_submit",produces = CHARSET_UTF8_JSON)
    @ResponseBody
    public String edit_submit(ArticleCu articleCu){
        User user = getUser();
        if(user == null){
            return  RestFulResultUtil.fail("登录已超时，请另开一个页面登录之后，再提交本次操作").serializeJson();
        }
        iArticleService.mod(articleCu,user.getAccount());
        JSONObject result = new JSONObject();
        result.put("result","success");
        result.put("redirectUrl",String.format("%s%s/article/details/%s.html",getDomain(),user.getAccount(),articleCu.getId()));
        return RestFulResultUtil.success(result).serializeJson();
    }

    /**
     * 删除文章
     * @param currentStatu 当前文章状态
     * @param toNewStatu 转移到的状态
     * @param articleId 文章id
     * @param remark 转移备注
     * @return
     */
    @RequestMapping(value = "/auth/article/delete/{articleId}/{currentStatu}/{toNewStatu}",method = RequestMethod.DELETE,produces = CHARSET_UTF8_JSON)
    @ResponseBody
    public String delete(@PathVariable int currentStatu,@PathVariable int toNewStatu,@PathVariable String articleId,String remark) throws Exception {
        User user = getUser();
        String msg = iArticleService.delete(articleId, user.getAccount(),user.getId(),currentStatu,toNewStatu,remark);
        if(msg != null){
            return ResultJsonUtil.failComm(msg);
        }
        return ResultJsonUtil.success("操作成功");
    }

    /**
     * 从回收站恢复文章
     * @param articleId
     * @return
     */
    @RequestMapping(value = "/auth/article/recovery/{articleId}",method = RequestMethod.PUT,produces = CHARSET_UTF8_JSON)
    @ResponseBody
    public String recovery(@PathVariable String articleId){
        User user = getUser();
        String msg = iArticleService.recovery(articleId, user.getAccount(),user.getId());
        if(msg != null){
            return ResultJsonUtil.failComm(msg);
        }
        return ResultJsonUtil.success("操作成功");
    }

    /**
     * 获取用户阅读数量排行榜?cd=readNum
     * @param account
     * @return
     */
    @RequestMapping(value = "/{account}/article/top",method = RequestMethod.GET,produces = CHARSET_UTF8_JSON)
    @ResponseBody
    public String userReadTopAtricles(@PathVariable("account") String account){
        List<ArticleCu> userTopAtricles = iArticleService.top(10,account);
        return RestFulResultUtil.success(userTopAtricles).serializeJson();
    }
    /**
     * 获取用户所有的文类
     * @param account
     * @return
     */
    @RequestMapping(value = "/{account}/article/categorys",method = RequestMethod.GET,produces = CHARSET_UTF8_JSON)
    @ResponseBody
    public String categorys(@PathVariable("account") String account){
        List<Category> categorys = iCategoryService.findAllByAccount(account);
        return RestFulResultUtil.success(categorys).serializeJson();
    }
    /**
     *
     * 获取全站热门文章?cd=readNum
     * @return
     */
    @RequestMapping(value = "/article/top",method = RequestMethod.GET,produces = CHARSET_UTF8_JSON)
    @ResponseBody
    public String topAtricles(){
        List<Article> topAtricles = iArticleCache.getAllTop(0,9,1);
        return RestFulResultUtil.success(topAtricles).serializeJson();
    }
    /**
     * 获取指定文章的分类列表
     * @param artId 文章id
     * @return
     */
    @RequestMapping(value = "/auth/article/{artId}/cats",method = RequestMethod.GET,produces = CHARSET_UTF8_JSON)
    @ResponseBody
    public String categorysByArtId(@PathVariable("artId") String artId){
        List<Category> categorys = iCategoryService.findArticleCat(artId);
        return RestFulResultUtil.success(categorys).serializeJson();
    }

    /**
     * 给指定文章增加或则删除分类
     * @param artId 文章id
     * @param catId 分类id
     * @return
     */
    @RequestMapping(value = "/auth/article/{artId}/cat/{catId}",method = RequestMethod.PUT,produces = CHARSET_UTF8_JSON)
    @ResponseBody
    public String catByArtId(@PathVariable("artId") String artId,@PathVariable("catId") String catId,boolean isAdd){
        iCategoryService.catByArtId(artId,catId,isAdd);
        return RestFulResultUtil.success("操作成功").serializeJson();
    }
}
